package com.chixing.ih.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

/**
 * @author 刘岩
 * @version 1.0
 * @Desc Practice makes perfect
 * @date 2020/9/11 12:53
 */
public class FileUtil {

    public static final HashMap<String, String> mFileTypes = new HashMap<String, String>();

    static {
        mFileTypes.put("89504E47", "png");
        mFileTypes.put("D0CF11E0", "doc");
        mFileTypes.put("25504446", "pdf");
        mFileTypes.put("504B0304", "zip");
        mFileTypes.put("00000000", "docx");
        mFileTypes.put("E4BDBFE5", "txt");
        mFileTypes.put("FFD8FFE0", "jpg");

    }

    public static String getFileHeader(MultipartFile file) {
        InputStream is = null;
        String value = null;
        try {
            is = file.getInputStream();
            byte[] b = new byte[4];
            is.read(b, 0, b.length);
            value = bytesToHexString(b);
        } catch (Exception e) {
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return value;
    }

    public static String getType(MultipartFile file) {
        String fileHeader = getFileHeader(file);
        String s = mFileTypes.get(fileHeader);
        return "." + s;
    }

    private static String bytesToHexString(byte[] src) {
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        String hv;
        for (int i = 0; i < src.length; i++) {
            hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
            if (hv.length() < 2) {
                builder.append(0);
            }
            builder.append(hv);
        }

        return builder.toString();
    }


}
